﻿using System.ComponentModel;

namespace Common.Core
{
    public static class EnumsHelper
    {
        /// <summary>
        /// 通过值，获取枚举
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>枚举</returns>
        public static T GetEnumByValue<T>(int value)
        {
            return GetEnumByName<T>(value.ToString());
        }

        /// <summary>
        /// 通过枚举字符串，获取枚举
        /// </summary>
        /// <param name="name">枚举值</param>
        /// <returns>枚举</returns>
        public static T GetEnumByName<T>(string name)
        {
            Type t = typeof(T);
            return (T)System.Enum.Parse(t, name);
        }

        /// <summary>
        /// 通过枚举，获取枚举的描述信息
        /// </summary>
        /// <typeparam name="T">任意枚举类型</typeparam>
        /// <param name="t">传入枚举泛型</param>
        /// <returns>得到对应描述</returns>
        public static string GetEnumDesc<T>(T t)
        {
            var enumInfo = t.GetType().GetField(t.ToString());
            if (enumInfo == null)
            {
                return "";
            }
            var enumAttributes = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return enumAttributes.Length > 0 ? enumAttributes[0].Description : t.ToString();
        }
    }
}
